package platform

import (
	"context"
	"net/http"
	"strings"

	"gitee.com/wangshh_123/cross-pay-go/src/middleware"
	platformCommon "gitee.com/wangshh_123/cross-pay-go/src/platform/common"
	"gitee.com/wangshh_123/cross-pay-go/src/platform/integration"
	utilsCommon "gitee.com/wangshh_123/cross-pay-go/src/utils/common"
	"github.com/gin-gonic/gin"
)

// CardholderController 统一的持卡人控制器
// 使用工厂模式处理不同平台的持卡人操作
type CardholderController struct {
	platformManager *integration.PlatformManager
}

// NewCardholderController 创建持卡人控制器实例
func NewCardholderController() *CardholderController {
	return &CardholderController{
		platformManager: integration.GetGlobalPlatformManager(),
	}
}

// GetCardholderList 获取持卡人列表
// 根据用户的平台类型自动选择对应的平台进行查询
func (c *CardholderController) GetCardholderList(ctx *gin.Context) {
	// 从中间件获取平台信息
	platformInfo, exists := middleware.GetPlatformInfoFromContext(ctx)
	if !exists {
		utilsCommon.Error(ctx, http.StatusUnauthorized, "platform_info_not_found", nil)
		return
	}

	// 获取分页参数并添加验证
	pageIndex := int64(1)
	pageSize := int64(10)

	if page, err := utilsCommon.GetInt64Query(ctx, "pageIndex"); err == nil && page > 0 && page <= 1000 {
		pageIndex = page
	} else if err != nil {
		utilsCommon.Error(ctx, http.StatusBadRequest, "invalid_page_index", err)
		return
	}

	if size, err := utilsCommon.GetInt64Query(ctx, "pageSize"); err == nil && size > 0 && size <= 100 {
		pageSize = size
	} else if err != nil {
		utilsCommon.Error(ctx, http.StatusBadRequest, "invalid_page_size", err)
		return
	}

	// 获取查询参数
	cardholderID := ctx.Query("cardholderId")
	status := ctx.Query("status")
	name := ctx.Query("name")
	firstName := ctx.Query("firstName")
	lastName := ctx.Query("lastName")
	createdAtStart := ctx.Query("createdAtStart")
	createdAtEnd := ctx.Query("createdAtEnd")

	// 处理姓名参数的大小写转换
	if firstName != "" {
		firstName = strings.ToUpper(firstName)
	}
	if lastName != "" {
		lastName = strings.ToUpper(lastName)
	}
	if name != "" {
		name = strings.ToUpper(name)
	}

	// 构建持卡人列表查询请求
	request := &platformCommon.CardholderListRequest{
		PageIndex:     pageIndex,
		PageSize:      pageSize,
		MatrixAccount: platformInfo.MatrixAccount,
		FirstName:     firstName,
		LastName:      lastName,
		Name:          name,
	}

	// 创建包含查询参数的上下文
	requestCtx := context.WithValue(ctx.Request.Context(), "cardholder_id", cardholderID)
	requestCtx = context.WithValue(requestCtx, "status", status)
	requestCtx = context.WithValue(requestCtx, "name", name)
	requestCtx = context.WithValue(requestCtx, "first_name", firstName)
	requestCtx = context.WithValue(requestCtx, "last_name", lastName)
	requestCtx = context.WithValue(requestCtx, "created_at_start", createdAtStart)
	requestCtx = context.WithValue(requestCtx, "created_at_end", createdAtEnd)

	// 使用工厂模式处理请求
	result, err := c.platformManager.HandleRequest(requestCtx, platformInfo.PlatformType, "cardholder_list", request)
	if err != nil {
		utilsCommon.Error(ctx, http.StatusInternalServerError, "get_cardholder_list_failed", err)
		return
	}

	// 返回成功响应
	utilsCommon.Success(ctx, gin.H{
		"platform": platformInfo.PlatformType,
		"data":     result,
	})
}

// CreateCardholder 创建持卡人
// 根据用户的平台类型自动选择对应的平台进行创建
func (c *CardholderController) CreateCardholder(ctx *gin.Context) {
	// 从中间件获取平台信息
	platformInfo, exists := middleware.GetPlatformInfoFromContext(ctx)
	if !exists {
		utilsCommon.Error(ctx, http.StatusUnauthorized, "platform_info_not_found", nil)
		return
	}

	// 从上下文中获取用户ID
	userID, exists := ctx.Get("user_id")
	if !exists {
		utilsCommon.Error(ctx, http.StatusUnauthorized, "user_info_not_found", nil)
		return
	}

	// 类型断言检查
	id, ok := userID.(int64)
	if !ok {
		utilsCommon.Error(ctx, http.StatusInternalServerError, "invalid_user_id", nil)
		return
	}

	// 解析请求体
	var requestBody struct {
		FirstName                  string `json:"firstName" binding:"required"`
		LastName                   string `json:"lastName" binding:"required"`
		CardholderNameAbbreviation string `json:"cardholderNameAbbreviation"`
		Email                      string `json:"email" binding:"required,email"`
		Mobile                     string `json:"mobile" binding:"required"`
		MobilePrefix               string `json:"mobilePrefix"`
		DateOfBirth                string `json:"dateOfBirth"`
		CertType                   string `json:"certType"`
		Portrait                   string `json:"portrait"`
		ReverseSide                string `json:"reverseSide"`
		NationalityCountryCode     string `json:"nationalityCountryCode"`
		ResidentialAddress         string `json:"residentialAddress"`
		ResidentialCity            string `json:"residentialCity"`
		ResidentialCountryCode     string `json:"residentialCountryCode"`
		ResidentialPostalCode      string `json:"residentialPostalCode"`
		ResidentialState           string `json:"residentialState"`
	}

	if err := ctx.ShouldBindJSON(&requestBody); err != nil {
		utilsCommon.Error(ctx, http.StatusBadRequest, "invalid_request_body", err)
		return
	}

	// 额外的输入验证
	if len(requestBody.FirstName) > 50 || len(requestBody.LastName) > 50 {
		utilsCommon.Error(ctx, http.StatusBadRequest, "name_too_long", nil)
		return
	}

	if len(requestBody.Email) > 100 {
		utilsCommon.Error(ctx, http.StatusBadRequest, "email_too_long", nil)
		return
	}

	if len(requestBody.Mobile) > 20 {
		utilsCommon.Error(ctx, http.StatusBadRequest, "mobile_too_long", nil)
		return
	}

	// 构建创建持卡人请求
	request := &platformCommon.CreateCardholderRequest{
		UserID:                     id,
		FirstName:                  requestBody.FirstName,
		LastName:                   requestBody.LastName,
		CardholderNameAbbreviation: requestBody.CardholderNameAbbreviation,
		Email:                      requestBody.Email,
		Mobile:                     requestBody.Mobile,
		MobilePrefix:               requestBody.MobilePrefix,
		DateOfBirth:                requestBody.DateOfBirth,
		CertType:                   requestBody.CertType,
		Portrait:                   requestBody.Portrait,
		ReverseSide:                requestBody.ReverseSide,
		NationalityCountryCode:     requestBody.NationalityCountryCode,
		ResidentialAddress:         requestBody.ResidentialAddress,
		ResidentialCity:            requestBody.ResidentialCity,
		ResidentialCountryCode:     requestBody.ResidentialCountryCode,
		ResidentialPostalCode:      requestBody.ResidentialPostalCode,
		ResidentialState:           requestBody.ResidentialState,
	}

	// 使用工厂模式处理请求
	result, err := c.platformManager.HandleRequestWithGinContext(ctx, platformInfo.PlatformType, "create_cardholder", request)
	if err != nil {
		utilsCommon.Error(ctx, http.StatusInternalServerError, "create_cardholder_failed", err)
		return
	}

	// 返回成功响应
	utilsCommon.Success(ctx, gin.H{
		"platform": platformInfo.PlatformType,
		"data":     result,
	})
}

// UpdateCardholder 更新持卡人
// 根据用户的平台类型自动选择对应的平台进行更新
func (c *CardholderController) UpdateCardholder(ctx *gin.Context) {
	// 从中间件获取平台信息
	platformInfo, exists := middleware.GetPlatformInfoFromContext(ctx)
	if !exists {
		utilsCommon.Error(ctx, http.StatusUnauthorized, "platform_info_not_found", nil)
		return
	}

	// 解析请求体
	var requestBody struct {
		MatrixAccount              string `json:"matrixAccount" binding:"required"`
		FirstName                  string `json:"firstName"`
		LastName                   string `json:"lastName"`
		CardholderNameAbbreviation string `json:"cardholderNameAbbreviation"`
		Email                      string `json:"email"`
		Mobile                     string `json:"mobile"`
		MobilePrefix               string `json:"mobilePrefix"`
		DateOfBirth                string `json:"dateOfBirth"`
		CertType                   string `json:"certType"`
		Portrait                   string `json:"portrait"`
		ReverseSide                string `json:"reverseSide"`
		NationalityCountryCode     string `json:"nationalityCountryCode"`
		ResidentialAddress         string `json:"residentialAddress"`
		ResidentialCity            string `json:"residentialCity"`
		ResidentialCountryCode     string `json:"residentialCountryCode"`
		ResidentialPostalCode      string `json:"residentialPostalCode"`
		ResidentialState           string `json:"residentialState"`
		CardholderID               string `json:"cardholderId" binding:"required"`
		Status                     string `json:"status"`
	}

	if err := ctx.ShouldBindJSON(&requestBody); err != nil {
		utilsCommon.Error(ctx, http.StatusBadRequest, "invalid_request_body", err)
		return
	}

	// 验证MatrixAccount是否匹配
	if requestBody.MatrixAccount != platformInfo.MatrixAccount {
		utilsCommon.Error(ctx, http.StatusForbidden, "matrix_account_mismatch", nil)
		return
	}

	// 根据MatrixAccount判断平台类型
	platformType := platformInfo.PlatformType
	if platformType != "photonpay" && platformType != "hlpay" {
		utilsCommon.Error(ctx, http.StatusBadRequest, "unsupported_platform", nil)
		return
	}

	// 构建更新持卡人请求，所有字段都传递
	request := &platformCommon.UpdateCardholderRequest{
		CardholderID:               requestBody.CardholderID,
		FirstName:                  requestBody.FirstName,
		LastName:                   requestBody.LastName,
		CardholderNameAbbreviation: requestBody.CardholderNameAbbreviation,
		Email:                      requestBody.Email,
		Mobile:                     requestBody.Mobile,
		MobilePrefix:               requestBody.MobilePrefix,
		DateOfBirth:                requestBody.DateOfBirth,
		CertType:                   requestBody.CertType,
		Portrait:                   requestBody.Portrait,
		ReverseSide:                requestBody.ReverseSide,
		NationalityCountryCode:     requestBody.NationalityCountryCode,
		ResidentialAddress:         requestBody.ResidentialAddress,
		ResidentialCity:            requestBody.ResidentialCity,
		ResidentialCountryCode:     requestBody.ResidentialCountryCode,
		ResidentialPostalCode:      requestBody.ResidentialPostalCode,
		ResidentialState:           requestBody.ResidentialState,
		Status:                     requestBody.Status,
	}

	// 使用工厂模式处理请求
	result, err := c.platformManager.HandleRequestWithGinContext(ctx, platformType, "update_cardholder", request)
	if err != nil {
		utilsCommon.Error(ctx, http.StatusInternalServerError, "update_cardholder_failed", err)
		return
	}

	// 返回成功响应
	utilsCommon.Success(ctx, gin.H{
		"platform": platformType,
		"data":     result,
	})
}

// GetCardholderListByPlatform 根据指定平台获取持卡人列表
// 允许管理员或高级用户查询指定平台的持卡人列表
func (c *CardholderController) GetCardholderListByPlatform(ctx *gin.Context) {
	// 从URL参数获取平台类型
	platformType := ctx.Param("platform")
	if platformType == "" {
		utilsCommon.Error(ctx, http.StatusBadRequest, "platform_parameter_required", nil)
		return
	}

	// 验证平台类型是否有效
	if platformType != "photonpay" && platformType != "hlpay" {
		utilsCommon.Error(ctx, http.StatusBadRequest, "unsupported_platform", nil)
		return
	}

	// 获取分页参数并添加验证
	pageIndex := int64(1)
	pageSize := int64(10)

	if page, err := utilsCommon.GetInt64Query(ctx, "pageIndex"); err == nil && page > 0 && page <= 1000 {
		pageIndex = page
	} else if err != nil {
		utilsCommon.Error(ctx, http.StatusBadRequest, "invalid_page_index", err)
		return
	}

	if size, err := utilsCommon.GetInt64Query(ctx, "pageSize"); err == nil && size > 0 && size <= 100 {
		pageSize = size
	} else if err != nil {
		utilsCommon.Error(ctx, http.StatusBadRequest, "invalid_page_size", err)
		return
	}

	// 获取查询参数
	cardholderID := ctx.Query("cardholderId")
	status := ctx.Query("status")
	name := ctx.Query("name")
	firstName := ctx.Query("firstName")
	lastName := ctx.Query("lastName")
	createdAtStart := ctx.Query("createdAtStart")
	createdAtEnd := ctx.Query("createdAtEnd")

	// 处理姓名参数的大小写转换
	if firstName != "" {
		firstName = strings.ToUpper(firstName)
	}
	if lastName != "" {
		lastName = strings.ToUpper(lastName)
	}
	if name != "" {
		name = strings.ToUpper(name)
	}

	// 构建持卡人列表查询请求
	request := &platformCommon.CardholderListRequest{
		PageIndex: pageIndex,
		PageSize:  pageSize,
		FirstName: firstName,
		LastName:  lastName,
		Name:      name,
	}

	// 创建包含查询参数的上下文
	requestCtx := context.WithValue(ctx.Request.Context(), "cardholder_id", cardholderID)
	requestCtx = context.WithValue(requestCtx, "status", status)
	requestCtx = context.WithValue(requestCtx, "name", name)
	requestCtx = context.WithValue(requestCtx, "first_name", firstName)
	requestCtx = context.WithValue(requestCtx, "last_name", lastName)
	requestCtx = context.WithValue(requestCtx, "created_at_start", createdAtStart)
	requestCtx = context.WithValue(requestCtx, "created_at_end", createdAtEnd)

	// 使用工厂模式处理请求
	result, err := c.platformManager.HandleRequest(requestCtx, platformType, "cardholder_list", request)
	if err != nil {
		utilsCommon.Error(ctx, http.StatusInternalServerError, "get_cardholder_list_failed", err)
		return
	}

	// 返回成功响应
	utilsCommon.Success(ctx, gin.H{
		"platform": platformType,
		"data":     result,
	})
}

// CreateCardholderByPlatform 根据指定平台创建持卡人
// 允许管理员或高级用户在指定平台创建持卡人
func (c *CardholderController) CreateCardholderByPlatform(ctx *gin.Context) {
	// 从URL参数获取平台类型
	platformType := ctx.Param("platform")
	if platformType == "" {
		utilsCommon.Error(ctx, http.StatusBadRequest, "platform_parameter_required", nil)
		return
	}

	// 验证平台类型是否有效
	if platformType != "photonpay" && platformType != "hlpay" {
		utilsCommon.Error(ctx, http.StatusBadRequest, "unsupported_platform", nil)
		return
	}

	// 解析请求体
	var requestBody struct {
		FirstName string `json:"firstName" binding:"required"`
		LastName  string `json:"lastName" binding:"required"`
		Email     string `json:"email" binding:"required,email"`
		Mobile    string `json:"mobile" binding:"required"`
	}

	if err := ctx.ShouldBindJSON(&requestBody); err != nil {
		utilsCommon.Error(ctx, http.StatusBadRequest, "invalid_request_body", err)
		return
	}

	// 构建创建持卡人请求
	request := &platformCommon.CreateCardholderRequest{
		FirstName: requestBody.FirstName,
		LastName:  requestBody.LastName,
		Email:     requestBody.Email,
		Mobile:    requestBody.Mobile,
	}

	// 使用工厂模式处理请求
	result, err := c.platformManager.HandleRequest(ctx.Request.Context(), platformType, "create_cardholder", request)
	if err != nil {
		utilsCommon.Error(ctx, http.StatusInternalServerError, "create_cardholder_failed", err)
		return
	}

	// 返回成功响应
	utilsCommon.Success(ctx, gin.H{
		"platform": platformType,
		"data":     result,
	})
}

// UpdateCardholderByPlatform 根据指定平台更新持卡人
// 允许管理员或高级用户在指定平台更新持卡人
func (c *CardholderController) UpdateCardholderByPlatform(ctx *gin.Context) {
	// 从URL参数获取平台类型
	platformType := ctx.Param("platform")
	if platformType == "" {
		utilsCommon.Error(ctx, http.StatusBadRequest, "platform_parameter_required", nil)
		return
	}

	// 验证平台类型是否有效
	if platformType != "photonpay" && platformType != "hlpay" {
		utilsCommon.Error(ctx, http.StatusBadRequest, "unsupported_platform", nil)
		return
	}

	// 解析请求体
	var requestBody struct {
		MatrixAccount string `json:"matrixAccount" binding:"required"`
		FirstName     string `json:"firstName"`
		LastName      string `json:"lastName"`
		Email         string `json:"email"`
		Mobile        string `json:"mobile"`
		Status        string `json:"status"`
		CardholderID  string `json:"cardholderId" binding:"required"`
		// PhotonPay API 要求的字段
		DateOfBirth            string `json:"dateOfBirth"`
		NationalityCountryCode string `json:"nationalityCountryCode"`
		MobilePrefix           string `json:"mobilePrefix"`
		CertType               string `json:"certType"`
		Portrait               string `json:"portrait"`
		ReverseSide            string `json:"reverseSide"`
		ResidentialAddress     string `json:"residentialAddress"`
		ResidentialCity        string `json:"residentialCity"`
		ResidentialCountryCode string `json:"residentialCountryCode"`
		ResidentialPostalCode  string `json:"residentialPostalCode"`
		ResidentialState       string `json:"residentialState"`
	}

	if err := ctx.ShouldBindJSON(&requestBody); err != nil {
		utilsCommon.Error(ctx, http.StatusBadRequest, "invalid_request_body", err)
		return
	}

	// 构建更新持卡人请求
	request := &platformCommon.UpdateCardholderRequest{
		CardholderID: requestBody.CardholderID,
		FirstName:    requestBody.FirstName,
		LastName:     requestBody.LastName,
		Email:        requestBody.Email,
		Mobile:       requestBody.Mobile,
		Status:       requestBody.Status,
		// PhotonPay API 要求的字段
		DateOfBirth:            requestBody.DateOfBirth,
		NationalityCountryCode: requestBody.NationalityCountryCode,
		MobilePrefix:           requestBody.MobilePrefix,
		CertType:               requestBody.CertType,
		Portrait:               requestBody.Portrait,
		ReverseSide:            requestBody.ReverseSide,
		ResidentialAddress:     requestBody.ResidentialAddress,
		ResidentialCity:        requestBody.ResidentialCity,
		ResidentialCountryCode: requestBody.ResidentialCountryCode,
		ResidentialPostalCode:  requestBody.ResidentialPostalCode,
		ResidentialState:       requestBody.ResidentialState,
	}

	// 使用工厂模式处理请求
	result, err := c.platformManager.HandleRequest(ctx.Request.Context(), platformType, "update_cardholder", request)
	if err != nil {
		utilsCommon.Error(ctx, http.StatusInternalServerError, "update_cardholder_failed", err)
		return
	}

	// 返回成功响应
	utilsCommon.Success(ctx, gin.H{
		"platform": platformType,
		"data":     result,
	})
}

// GetSupportedPlatforms 获取支持持卡人操作的平台列表
func (c *CardholderController) GetSupportedPlatforms(ctx *gin.Context) {
	// 获取平台信息
	supportedPlatforms := c.platformManager.GetFactory().GetSupportedPlatforms()

	// 定义支持持卡人操作的平台列表
	supportedCardholderPlatforms := map[string]bool{
		"photonpay": true,
		"hlpay":     true,
	}

	platforms := make([]gin.H, 0, len(supportedPlatforms))
	for _, platformID := range supportedPlatforms {
		platformInfo, err := c.platformManager.GetPlatformInfo(platformID)
		if err != nil {
			continue
		}

		// 检查平台是否支持持卡人操作
		supportsCardholder := supportedCardholderPlatforms[platformID]

		platforms = append(platforms, gin.H{
			"platform":            platformID,
			"supports_cardholder": supportsCardholder,
			"supported_features":  platformInfo["supported_operations"],
			"config":              platformInfo["config"],
		})
	}

	utilsCommon.Success(ctx, gin.H{
		"platforms": platforms,
		"total":     len(platforms),
	})
}
